#pragma once

#include <string>
#include <cstring>
#include <strings.h>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <functional>
#include "InetAddr.hpp"
#include "Log.hpp"

//using func_t = std::function<std::string(const std::string &)>;

using hander_message_t = std::function<void (int sockfd, const std::string message, const InetAddr who)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, hander_message_t hander_message) : _sockfd(-1), _port(port), _isrunning(false),_hander_message(hander_message)
    {
    }

    void InitServer()
    {

        // 1.创建 udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);

        // 2.0 填充sockaddr_in 结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 这里sin_addr 里面还有一个结构体

        // 2.1 bind sockfd 和 网络信息
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            exit(1);
        }
    }

    void Start()
    {

        _isrunning = true;

        while (true)
        {
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);

            if (n > 0)
            {
                
                message[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d]: %s\n", addr.Ip().c_str(), addr.Port(), message);

                _hander_message(_sockfd, message, addr);

                //sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }

        _isrunning = false;
    }

    ~UdpServer()
    {
    }

private:
    uint16_t _port;
    int _sockfd;
    bool _isrunning;

    // 给服务器设定回调，用来让上层进行注册业务的处理方法
    hander_message_t _hander_message;
};